/*****************************************************************************
 * Copyright (c) 2022, Nations Technologies Inc.
 *
 * All rights reserved.
 * ****************************************************************************
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer below.
 *
 * Nations' name may not be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY NATIONS "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * DISCLAIMED. IN NO EVENT SHALL NATIONS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ****************************************************************************/

/**
 * @file main.c
 * @author Nations
 * @version V1.2.2
 *
 * @copyright Copyright (c) 2022, Nations Technologies Inc. All rights reserved.
 */

#include "sys_param.h"
#include "n32l40x_lptim.h"
/********
 * VCC = 3.0V, 即 3.0v----4096
 * 
 * ****/

// #define  DAC_OUTPUT_EN     1   // 用dac控制 ems输出电压
#define LPTIMER_PWM_CTRL    1    //  用 lptimer控制ems输出电压


#ifdef LPTIMER_PWM_CTRL

#define LP_PWM_BASE_COUNTER      (800)
#endif


typedef struct 
{
    LEVEL_e level;
    int dac_data;/* data */
}DAC_DATA_t;

DAC_DATA_t dac_voltage_item[] = {
#ifdef DAC_OUTPUT_EN
    {LEVEL_0, 0},  

    // ----------------以脸部为基础，脸部三档电压调整为1档
    {LEVEL_1, 2700},     
    {LEVEL_2, 2800},
    {LEVEL_3, 2900},
    {LEVEL_4, 3000},
    {LEVEL_5, 3100},
    {LEVEL_6, 3200},    
    {LEVEL_7, 3300},   
    {LEVEL_8, 3450},
    {LEVEL_9, 3600},   
    {LEVEL_10, 3750},
#else
    {LEVEL_0, LP_PWM_BASE_COUNTER},  
    {LEVEL_1, LP_PWM_BASE_COUNTER*45/100},     
    {LEVEL_2, LP_PWM_BASE_COUNTER*40/100},
    {LEVEL_3, LP_PWM_BASE_COUNTER*35/100},
    {LEVEL_4, LP_PWM_BASE_COUNTER*33/100},
    {LEVEL_5, LP_PWM_BASE_COUNTER*30/100},
    {LEVEL_6, LP_PWM_BASE_COUNTER*25/100},    
    {LEVEL_7, LP_PWM_BASE_COUNTER*23/100},   
    // {LEVEL_8, 200},
    // {LEVEL_9, 150},   
    // {LEVEL_10, 100}, 

#endif


};

static void my_lptimer_duty_change(int duty);

/**
 * @brief  Configures the different GPIO ports.
 */
static void dac_gpio_cfg(void)
{
#ifdef DAC_OUTPUT_EN    
    GPIO_InitType GPIO_InitStructure;
    GPIO_InitStruct(&GPIO_InitStructure);
    /* GPIOA Periph clock enable */
    RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOA, ENABLE);
    /* Once the DAC channel is enabled, the corresponding GPIO pin is automatically
       connected to the DAC converter. In order to avoid parasitic consumption,
       the GPIO pin should be configured in analog */
    GPIO_InitStructure.Pin       = GPIO_PIN_4;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Input;
    GPIO_InitStructure.GPIO_Pull = GPIO_No_Pull;
    //GPIO_InitStructure.GPIO_Pull = GPIO_Mode_AF_OD; 
    GPIO_InitPeripheral(GPIOA, &GPIO_InitStructure);
#endif    
}

/**
 * @brief  Configures the different GPIO ports.
 */
static void dac_channel_cfg(void)
{
#ifdef DAC_OUTPUT_EN     
    DAC_InitType DAC_InitStructure;

    /* DAC Periph clock enable */
    RCC_EnableAPB1PeriphClk(RCC_APB1_PERIPH_DAC, ENABLE);
    /* DAC channel1 Configuration */
    DAC_InitStructure.Trigger          = DAC_TRG_SOFTWARE;
    DAC_InitStructure.WaveGen          = DAC_WAVEGEN_NOISE;
    DAC_InitStructure.LfsrUnMaskTriAmp = DAC_UNMASK_LFSRBIT0;
    DAC_InitStructure.BufferOutput     = DAC_BUFFOUTPUT_ENABLE;
    DAC_Init(&DAC_InitStructure);

    /* Enable DAC Channel1: Once the DAC channel1 is enabled, PA.04 is
       automatically connected to the DAC converter. */
      
    DAC_Enable(ENABLE);

    /* Set DAC Channel1 DHR12L register */
    //DAC_SetChData(DAC_ALIGN_R_12BIT, 4094);
    DAC_SetChData(DAC_ALIGN_R_12BIT, 1024);
#endif    
}

void ems_voltage_select(void)
{
#ifdef DAC_OUTPUT_EN     
    int i;

    for(i = 0; i < sizeof(dac_voltage_item)/sizeof(dac_voltage_item[0]); i ++)
    {
        if(sys_data.level == dac_voltage_item[i].level){
            break;
        }
    }
    if(i == sizeof(dac_voltage_item)/sizeof(dac_voltage_item[0]))
    {
		printf("\n\r dac_index not match \n\r");
        return;
    }

    DAC_SetChData(DAC_ALIGN_R_12BIT, dac_voltage_item[i].dac_data);
    DAC_SoftTrgEnable(ENABLE);
//	printf("\n\r set_dac_data:%d \n\r", dac_voltage_item[i].dac_data);
#endif
}

void ems_voltage_percent_select(int percent)
{
    
    int i;

    for(i = 0; i < sizeof(dac_voltage_item)/sizeof(dac_voltage_item[0]); i ++)
    {
        if(sys_data.ems_level == dac_voltage_item[i].level){
            break;
        }
    }
    if(i == sizeof(dac_voltage_item)/sizeof(dac_voltage_item[0]))
    {
		//printf("\n\r dac_index not match \n\r");
        return;
    }

    if(percent > 100){
        percent = 100;
    }
#ifdef DAC_OUTPUT_EN  
	// max 模式，档位电压比其他模式的电压高;
    if(MAX_MODE == get_sys_mode()){
        DAC_SetChData(DAC_ALIGN_R_12BIT, 320 + (dac_voltage_item[i].dac_data)*percent/100);
    }
    else if(BODY_MODE == get_sys_mode()){
        DAC_SetChData(DAC_ALIGN_R_12BIT, 200 + (dac_voltage_item[i].dac_data)*percent/100);
    }
    else{
        DAC_SetChData(DAC_ALIGN_R_12BIT, (dac_voltage_item[i].dac_data)*percent/100);
    }
    
    DAC_SoftTrgEnable(ENABLE);
	// printf("\n\r set_dac_data:,%d \n\r", dac_voltage_item[i].dac_data*percent/100);
#else

    
    ((dac_voltage_item[i].dac_data)*percent/100);
    // my_lptimer_duty_change((dac_voltage_item[i].dac_data));

#endif    
}



/**
 * @brief  output IO Initaliza.
 * @param NONE.
 *   This parameter can be one of following parameters:
 *     @arg NONE
 */
void LPTIM_OutputIoInit(void)
{
    GPIO_InitType GPIO_InitStructure;
    GPIO_InitStruct(&GPIO_InitStructure);

	    /* Enable the GPIO Clock */
    RCC_EnableAPB2PeriphClk(RCC_APB2_PERIPH_GPIOB, ENABLE);

    /* Configure the GPIO pin */
    GPIO_InitStructure.Pin        = GPIO_PIN_2;
    GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Alternate = GPIO_AF2_LPTIM;
    GPIO_InitPeripheral(GPIOB, &GPIO_InitStructure);
}

void lptiemr_gpi_deinit(void)
{
    gpio_output_cfg(GPIOB, GPIO_PIN_2);
	set_pin_low(GPIOB, GPIO_PIN_2);
}

/**************************************************************************
*
*************************************************************************/
static void my_lptimer_duty_change(int duty)
{
    lptiemr_gpi_deinit();
    LPTIM_DisableIT_CMPOK(LPTIM);
    LPTIM_Disable(LPTIM);


    LPTIM_OutputIoInit();
    LPTIM_Enable(LPTIM);

   
    /* config ARR ande compare register */ 
    // LPTIM_SetAutoReload(LPTIM, LP_PWM_BASE_COUNTER);    
    if(duty > LP_PWM_BASE_COUNTER){
        LPTIM_SetCompare(LPTIM, LP_PWM_BASE_COUNTER);
    }else{
        LPTIM_SetCompare(LPTIM, duty);
    }  
    // LPTIM_SetCompare(LPTIM, duty);
    //  LPTIM_SetCompare(LPTIM, LP_PWM_BASE_COUNTER/4);  

    LPTIM_StartCounter(LPTIM, LPTIM_OPERATING_MODE_CONTINUOUS); 
    
     
}



/**************************************************************************
*
*************************************************************************/
static void my_lptimer_init(void)
{
 /* Enable the LSI source */
    // RCC_EnableLsi(ENABLE);	
    RCC_ConfigLPTIMClk(RCC_LPTIMCLK_SRC_HSI);
    RCC_EnableRETPeriphClk(RCC_RET_PERIPH_LPTIM, ENABLE);
    /* Init output IO */
    LPTIM_SetPrescaler(LPTIM, LPTIM_PRESCALER_DIV1);
    LPTIM_OutputIoInit();
    /* Init lptim module */ 
    LPTIM->INTEN = 0x7F;


    LPTIM_SetWaveform(LPTIM, LPTIM_OUTPUT_WAVEFORM_PWM); 
    /* output wave */ 
    LPTIM_SetPolarity(LPTIM, LPTIM_OUTPUT_POLARITY_INVERSE);  //LPTIM_OUTPUT_POLARITY_INVERSE  LPTIM_OUTPUT_POLARITY_REGULAR
    /* config the prescaler */          
    LPTIM_EnableIT_CMPOK(LPTIM);

    LPTIM_Enable(LPTIM);
    /* config ARR ande compare register */ 
    LPTIM_SetAutoReload(LPTIM, LP_PWM_BASE_COUNTER);        
    LPTIM_SetCompare(LPTIM, LP_PWM_BASE_COUNTER/2);
    //while(!(LPTIM->INTSTS & LPTIM_INTSTS_CMPUPD));
    LPTIM_StartCounter(LPTIM, LPTIM_OPERATING_MODE_CONTINUOUS); 

}


/**************************************************************************
 * EMS电压 控制：
 *  1. 用dac 控制
 *  2. 用lptimer pwm控制 pb2，25khz，默认 80%占空比，占空比越大，后面输出的电压越小
 * 
*************************************************************************/
void my_dac_init(void)
{
#ifdef DAC_OUTPUT_EN      
    dac_gpio_cfg();
    dac_channel_cfg();
    DAC_SoftTrgEnable(ENABLE);
#else
    my_lptimer_init();
#endif    
}
